﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Extensions;
using System.Text.RegularExpressions;

namespace Core
{
    public class ServiceLine : Line
    {
        public bool ParseAscii { get { return LineTemplates.ParseAscii.IsMatch(Text); } }
        public bool DeliveringMessage { get { return LineTemplates.DeliveringMessage.IsMatch(Text); } }

        public ServiceLine(String rawLine, String[] columns)
            : base(rawLine, columns)
        {
        }

        public override void Chain(Chainer chainer)
        {
            if (ParseAscii)
                return;
            if (DeliveringMessage)
            {
                chainer.OpenChain(this);
                return;
            }

            int? createSerial = DetermineSerial(LineTemplates.CreatingSession.Match(Text));
            if (createSerial != null)
                chainer.AppendToChainBySession(this, createSerial.Value);
            else
                chainer.AppendToChain(this);
        }

        public int? DetermineSerial(Match serial)
        {
            return (serial.Success) ? Convert.ToInt32(serial.Groups["SessionId"].Value) : (int?)null;
        }

        protected override void Parse(String[] columns)
        {
            ThreadId = columns[1].ParseInt();
            TimeStamp = columns[2].ParseDateTime();
            Text = columns[3];
        }
    }
}
